package net.template.service.controller;

import net.template.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public abstract class BaseController {

    final Logger logger = LoggerFactory.getLogger(BaseController.class);
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 拦截所有控制器抛出的Exception，转换为HTTP 400错误返回客户端
     * @param manve
     *
     * @return  response
     *            HttpServletResponse
     * @throws IOException
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> parameterExceptionHandler(MethodArgumentNotValidException manve) {
        Result<Void> response = new Result<Void>();
        response.setErrorCode(-1);
        response.setErrorMessage(manve.getBindingResult().getFieldError().getDefaultMessage());
        return response;
    }

    /**
     * 拦截所有控制器抛出的BusinessException，根据该异常设置返回信息
     *
     * @param be
     *            拦截的BusinessException
     * @return payload:{success:false,errorCode:String, errorMessage:String}
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> businessExceptionHandler(HttpServletRequest request, BusinessException be) {
        logger.info(String.valueOf(be.getErrorCode()), be);
        Result<Void> response = Result.failed(be);
        return response;
    }

    protected final String fuzzy(String text) {
        return new StringBuilder("%").append(text).append("%").toString();
    }

    public String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

}
